import axios from 'axios'
import Qs from 'qs'
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

export function request(config) {

  // 1创建axios实例
  const instance = axios.create({
    baseURL: 'http://localhost:8082',//测试
    // baseURL: 'http://oa.mtzxgf.cn:8082',//正式
    timeout: 5000
  })

  //2.请求拦截器
  instance.interceptors.request.use(config => {
    //开启进度条
    NProgress.start()
    //添加请求头
    const  token = window.sessionStorage.getItem('token')
    // const  token = '2cf785d081103917c72f592bdfd027df'
    config.headers.common = {'X-token': token};

    return config
  },err => {
    console.log(err);
  })

  //2.1响应拦截器
  instance.interceptors.response.use(res => {
    //关闭进度条
    NProgress.done()
    return res.data
  },err => {
    console.log(err);
  })

  //3.发送请求
  return instance(config)
}


//封装的get，post请求

//get请求
export function get(params) {
  return request({
    url: params.url,
    params: params.data
  })
}

//postJson请求
export function postJson(params) {
  return request({
    headers: {
      'Content-Type': 'application/json'
    },
    transformRequest: [function (data) {
      data = JSON.stringify(data)
      return data
    }],
    url: params.url,
    method: 'post',
    data: params.data
  })
}

//post表单请求请求
export function postForm(params) {
  return request({
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    transformRequest: [function(data) {      //在请求之前对data传参进行格式转换
      data = Qs.stringify(data)
      return data
    }],
    url: params.url,                           //接口地址
    method: 'post',                             //请求类型
    data: params.data
  })
}


